﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;

namespace Medianamik.Core.Logging
{
    internal class LogSaver
    {
        private readonly HttpApplication _app;
        private static Thread _thread;
        private static readonly object _lock = new object();

        public LogSaver(HttpApplication app)
        {
            _app = app;
        }

        public static void SaveLogs(LogSaver saver, bool waitForEnd)
        {
            if (_thread == null || !_thread.IsAlive)
            {
                lock (_lock)
                {
                    if (_thread == null || !_thread.IsAlive)
                    {
                        _thread = new Thread(saver.WorkerMethod);
                        _thread.Start();
                        if (waitForEnd)
                            _thread.Join();
                    }
                }
            }
        }

        private void WorkerMethod()
        {
            ActivityLogger.SaveLogsToDb(_app);
        }
    }
}
